package org.tgcloud.group.service.manager;

import cn.hutool.core.util.ObjUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.tgcloud.group.core.APPResultMessage;
import org.tgcloud.group.core.ResultMessage;
import org.tgcloud.group.core.StringUtil;
import org.tgcloud.group.core.session.SessionFactory;
import org.tgcloud.group.entity.LogInfo;
import org.tgcloud.group.entity.MjNormalUser;
import org.tgcloud.group.repository.LogInfoMapper;
import org.tgcloud.group.repository.MjNormalUserMapper;
import org.tgcloud.group.web.controller.dto.user.SelectionUserDTO;
import org.tgcloud.group.web.controller.dto.user.UserDTO;
import org.tgcloud.group.web.controller.req.user.ManageUserEditReq;
import org.tgcloud.group.web.controller.req.user.ManageUserAddReq;
import org.tgcloud.group.web.controller.req.user.ManageUserNameReq;
import org.tgcloud.group.web.controller.req.user.UserTypeReq;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author: zhy
 * @create: 2023-08-22 11:23
 * @description:
 */
@Service
public class NormalUserManageService {

    @Autowired
    private MjNormalUserMapper userMapper;

    @Autowired
    private LogInfoMapper logInfoMapper;

    @Autowired
    private SessionFactory sessionFactory;

    public APPResultMessage<Object, UserDTO> getUserList(Integer pageNum, Integer pageSize, String keyword, Date startTime, Date endTime,
                                                         Short userType,Short isAssistant,Integer userId,String roleIds) {
        if (pageNum != null && pageSize != null){
            PageHelper.startPage(pageNum,pageSize);
            List<UserDTO> users = userMapper.selectManageListByKeyword(keyword, startTime, endTime, userType,isAssistant,userId);
            for (UserDTO user : users) {
                StringBuilder assistantUserNamesBuilder = new StringBuilder();
                //如果是助理，将开拓者id换为开拓者名称
                if (StringUtil.isNotBlank(user.getAssistantUserIds()) &&  user.getIsAssistant() == 2 ){
                    for (String userId2 : user.getAssistantUserIds().trim().split(",")) {
                        MjNormalUser mjNormalUser = userMapper.selectByPrimaryKey(Integer.parseInt(userId2));
                        // 检查查询结果是否有效
                        if (mjNormalUser != null) {
                            // 添加nickName到assistantUserNamesBuilder，并用逗号分隔
                            if (assistantUserNamesBuilder.length() > 0) {
                                assistantUserNamesBuilder.append(",");
                            }
                            assistantUserNamesBuilder.append(mjNormalUser.getNickName());
                        }
                    }
                }
                user.setAssistantUserNames(assistantUserNamesBuilder.toString());
                if (StringUtil.isNotBlank(roleIds)
                        && StringUtil.containsString(roleIds.split(","), "56")){
                    user.setTelephone(StringUtil.isNotBlank(user.getTelephone()) ? "******" : null);
                }
            }
            PageInfo<UserDTO> tables = new PageInfo<>(users);
            ResultMessage result = ResultMessage.builder().setList(tables.getList()).setAllPageNumber(tables.getPages()).setCount(tables.getTotal());
            APPResultMessage<Object, UserDTO> message = APPResultMessage.getSuccessMessage();
            message.setResult(result);
            return message;
        }else {
            List<UserDTO> users = userMapper.selectManageListByKeyword(keyword, startTime, endTime, userType,isAssistant,userId);
            for (UserDTO user : users) {
                StringBuilder assistantUserNamesBuilder = new StringBuilder();
                //如果是助理，将开拓者id换为开拓者名称
                if (StringUtil.isNotBlank(user.getAssistantUserIds()) &&  user.getIsAssistant() == 2 ){
                    for (String userId2 : user.getAssistantUserIds().trim().split(",")) {
                        MjNormalUser mjNormalUser = userMapper.selectByPrimaryKey(Integer.valueOf(userId2));
                        // 检查查询结果是否有效
                        if (mjNormalUser != null) {
                            // 添加nickName到assistantUserNamesBuilder，并用逗号分隔
                            if (assistantUserNamesBuilder.length() > 0) {
                                assistantUserNamesBuilder.append(",");
                            }
                            assistantUserNamesBuilder.append(mjNormalUser.getNickName());
                        }
                    }
                }
                user.setAssistantUserNames(assistantUserNamesBuilder.toString());
                if (StringUtil.isNotBlank(roleIds)
                        && StringUtil.containsString(roleIds.split(","), "56")){
                    user.setTelephone(StringUtil.isNotBlank(user.getTelephone()) ? "******" : null);
                }
            }
            ResultMessage resultMessage = ResultMessage.builder().setList(users);
            APPResultMessage<Object, UserDTO> successMessage = APPResultMessage.getSuccessMessage();
            successMessage.setResult(resultMessage);
            return successMessage;
        }
    }

    public APPResultMessage<Object, MjNormalUser> selectPushList(Short isAssistant) {
         {
             List<MjNormalUser> mjNormalUsers = userMapper.selectPushList(isAssistant);
             ResultMessage resultMessage = ResultMessage.builder().setList(mjNormalUsers);
            APPResultMessage<Object, MjNormalUser> successMessage = APPResultMessage.getSuccessMessage();
            successMessage.setResult(resultMessage);
            return successMessage;
        }
    }
    public APPResultMessage<Object, MjNormalUser> selectAssistantList(Integer assistantUserId) {
        {
            List<MjNormalUser> mjNormalUsers = userMapper.selectAssistantList(assistantUserId);
            ResultMessage resultMessage = ResultMessage.builder().setList(mjNormalUsers);
            APPResultMessage<Object, MjNormalUser> successMessage = APPResultMessage.getSuccessMessage();
            successMessage.setResult(resultMessage);
            return successMessage;
        }
    }

    public APPResultMessage<Object, List> doUpdateUserType(UserTypeReq req) {
        userMapper.updateUserTypeByUserId(req.getUserId(),req.getUserType());
        doDelToken(req.getUserId());
        return APPResultMessage.getSuccessMessage();
    }


    public APPResultMessage doUpdateUserName(ManageUserNameReq req) {
        userMapper.updateUserNameByUserId(req.getUserId(),req.getUsername());
        doDelToken(req.getUserId());
        return APPResultMessage.getSuccessMessage();
    }

    public void doDelToken(Integer userId){
        logInfoMapper.updateDelStatusByUserId(userId);
    }

    public APPResultMessage doAddUser(ManageUserAddReq req) {
        MjNormalUser user = userMapper.selectMsgByTelephone(req.getTelephone());
        if (user != null){
            return new APPResultMessage(6000, "该手机号的账户已被添加");
        }
        if (req.getUserType() != null && req.getUserType() == 1 && req.getPushUserId() == null){
            return new APPResultMessage(6001, "请选择渠道开拓者");
        }
        MjNormalUser normalUser = new MjNormalUser();
        normalUser.setNickName(req.getNickName());
        normalUser.setSex(req.getSex());
        normalUser.setStatus((short) 1);
        normalUser.setUserType(req.getUserType());
        normalUser.setTelephone(req.getTelephone());
        normalUser.setProvince(req.getProvince());
        normalUser.setCity(req.getCity());
        normalUser.setArea(req.getArea());
        normalUser.setAddress(req.getAddress());
        normalUser.setDirectorName(req.getDirectorName());
        normalUser.setIdCard(req.getIdCard());
        normalUser.setPushUserId(req.getPushUserId());
        normalUser.setCreateTime(new Date());
        normalUser.setIsSubscribeMessage((short) 1);
        normalUser.setIsShowAll(req.getIsShowAll() == null ? (short) 1 : req.getIsShowAll());
        normalUser.setTouristType(req.getTouristType());
        normalUser.setMarginPrice(req.getMarginPrice());
        normalUser.setUserLevel(req.getUserLevel());
        normalUser.setIsAssistant(req.getIsAssistant() == null ? (short) 1 : req.getIsAssistant());
        normalUser.setAssistantUserIds(req.getAssistantUserIds() == null ? null : req.getAssistantUserIds());
        if (req.getMediaPartyId() != null){
            normalUser.setMediaPartyId(req.getMediaPartyId());
        }
        userMapper.insertSelective(normalUser);
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage doEditUser(ManageUserEditReq req) {
        MjNormalUser user = userMapper.selectMsgByTelephone(req.getTelephone());
        if (user != null && user.getId() != req.getUserId()){
            return new APPResultMessage(6001, "该手机号已被注册");
        }
        MjNormalUser normalUser = new MjNormalUser();
        normalUser.setNickName(req.getNickName());
        normalUser.setSex(req.getSex());
        normalUser.setUserType(req.getUserType());
        normalUser.setTelephone(req.getTelephone());
        normalUser.setProvince(req.getProvince());
        normalUser.setCity(req.getCity());
        normalUser.setArea(req.getArea());
        normalUser.setAddress(req.getAddress());
        normalUser.setDirectorName(req.getDirectorName());
        normalUser.setIdCard(req.getIdCard());
        normalUser.setPushUserId(req.getPushUserId());
        normalUser.setId(req.getUserId());
        normalUser.setTouristType(req.getTouristType());
        normalUser.setMarginPrice(req.getMarginPrice());
        normalUser.setUserLevel(req.getUserLevel());
        if (req.getMediaPartyId() != null){
            normalUser.setMediaPartyId(req.getMediaPartyId());
        }
        normalUser.setIsAssistant(req.getIsAssistant() == null ? (short) 1 : req.getIsAssistant());
        if (req.getIsAssistant() == (short) 1){
            normalUser.setAssistantUserIds("");
        } else {
            normalUser.setAssistantUserIds(req.getAssistantUserIds() == null ? null : req.getAssistantUserIds());
        }
        userMapper.updateByPrimaryKeySelective(normalUser);
        if (req.getAssistantUserIds() == null){
            userMapper.resetPoineer(req.getUserId());
        }
        if (req.getUserType() != 1){
            userMapper.updatePushUserIdIsNullById(req.getUserId());
        }
        LogInfo info = logInfoMapper.selectByUserId(normalUser.getId());
        if (info != null){
            sessionFactory.destroySession(info.getToken());
        }
        return APPResultMessage.getSuccessMessage();
    }


    public APPResultMessage getSelectionUserList() {
        List<SelectionUserDTO> dtoList = new ArrayList<SelectionUserDTO>();
        List<MjNormalUser> userList = userMapper.selectSelectionManageUserList();
        for (MjNormalUser user : userList){
            SelectionUserDTO userDTO = new SelectionUserDTO();
            userDTO.setUserId(user.getId());
            userDTO.setNickName(user.getNickName());
            List<MjNormalUser> subUserList = userMapper.selectSelectionAssistantUserList(user.getId());
            if (subUserList != null && !subUserList.isEmpty()){
                List<SelectionUserDTO> list = new ArrayList<>();
                for (MjNormalUser subUser : subUserList){
                    SelectionUserDTO userSubDTO = new SelectionUserDTO();
                    userSubDTO.setUserId(subUser.getId());
                    userSubDTO.setNickName(subUser.getNickName());
                    list.add(userSubDTO);
                }
                userDTO.setSelectionAssistantList(list);
            }
            dtoList.add(userDTO);
        }
        APPResultMessage message = APPResultMessage.getSuccessMessage();
        ResultMessage resultMessage = ResultMessage.builder().setList(dtoList);
        message.setResult(resultMessage);
        return message;
    }
}
